#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include "uv.h"
volatile int flag[3] = {0,0,0};
#define LOOP 10//5024

void example_task1(uv_work_t *data) {
    int *num = (int *)data;
    int j = -1;
    int k = 0;
    int t = 0;
    for	(int i = 0; i < 10; i++) {
        t = k;
        k = j;
        j = t;
    }
    __sync_fetch_and_add(&flag[0], 1);
}

void example_task2(uv_work_t *data) {
    int *num = (int *)data;
    float a = 1.1;
    float b = 2.2;
    float c = 3.3;
    for	(int i = 0; i < 10; i++) {
        a = b*c;
        b++;
    }
    __sync_fetch_and_add(&flag[1], 1);
}

void example_task3(uv_work_t *data) {
    int *num = (int *)data;
    long a = 4;
    long b = 5;
    long c = 6;
    for	(int i = 0; i < 10; i++) {
        a = a*a -1;
        b = b*b -4;
        c = c*c -3;
    }
    __sync_fetch_and_add(&flag[2], 1);
}

void after_fib(uv_work_t *req, int status)
{
//    fprintf(stderr, "Done calculating %dth fibonacci\n", *(int *) req->data);
}

// gcc *.c -lpthread -O2 -o m
int main() {
    
    // init pool
    uv_loop_t *Loop = uv_default_loop();
    
    int thread_count = 2; // 可根据需要设置 
    uv_update_time(Loop);
    
    
    uv_run(Loop, UV_RUN_NOWAIT);
    sleep(1);
    struct timespec ts;
    struct timespec ts2;
    int time[3] = {0,0,0};
    uv_work_t req[LOOP];
    for (int i= 0; i < 100000; i++)
    {
        clock_gettime(CLOCK_REALTIME, &ts);
        int loop = LOOP;
        while (loop--)
        {
            printf("[loop=%d] %d\n",loop,__LINE__);
            int data1 = 1;
            req[loop].data  = NULL;
            uv_queue_work(Loop, &req[loop], example_task1, NULL);

            printf("[loop=%d] %d\n",loop,__LINE__);
            int data2 = 2;
            req[loop].data  = NULL;
            uv_queue_work(Loop, &req[loop], example_task2, NULL);
            
            printf("[loop=%d] %d\n",loop,__LINE__);
            int data3 = 3;
            req[loop].data  = NULL;
            uv_queue_work(Loop, &req[loop], example_task3, NULL);
            // 等待任务执行完成
            // ...
        }
        printf("____ %d\n",__LINE__);
        while(flag[0]!=LOOP || flag[1]!=LOOP || flag[2]!=LOOP) {
            ;//sleep(1);
        }
        printf("____ %d\n",__LINE__);
        flag[0] = 0;
        flag[1] = 0;
        flag[2] = 0;
        clock_gettime(CLOCK_REALTIME, &ts2);

        time[0] = (ts2.tv_sec-ts.tv_sec)*1000000+(ts2.tv_nsec/1000)-(ts.tv_nsec/1000);
        time[1]+=time[0];
        time[2] =time[1]/(i+1);
        printf("[loop:%04d]cur_time:%04d us,avg_time:%04d us\n", i+1,time[0], time[2]);
    }
    uv_stop(Loop);
    uv_loop_delete(Loop);
    sleep(1);
    return 0;
}
